import React, { FC, useState } from "react";
import { useRequest, useTitle } from "ahooks";
import {
  Empty,
  Typography,
  Table,
  Tag,
  Button,
  Space,
  Modal,
  message,
  Spin,
} from "antd";
import { ExclamationCircleFilled } from "@ant-design/icons";
import ListSearch from "../../components/ListSearch";
import useLoadQuestionListData from "../../hooks/useLoadQuestionListData";
import styles from "./Common.module.scss";
import ListPage from "../../components/ListPage";
import {
  deleteQuestionService,
  updataQuestionService,
} from "../../services/question";
const { Title } = Typography;
const Trash: FC = () => {
  useTitle("星瑞问卷 -  回收站");
  const { confirm } = Modal;
  //自定义 hook 获取(查询）用户列表
  const {
    loading,
    data = {},
    refresh,
  } = useLoadQuestionListData({ isDeleted: true });
  const { list = [], total = 0 } = data;

  const tableColumns = [
    {
      title: "标题",
      dataIndex: "title",
    },
    {
      title: "是否发布",
      dataIndex: "isPublished",
      render: (isPublished: boolean) => {
        return isPublished ? (
          <Tag color="processing">已发布</Tag>
        ) : (
          <Tag>未发布</Tag>
        );
      },
    },
    {
      title: "答卷",
      dataIndex: "answerCount",
    },
    {
      title: "创建时间",
      dataIndex: "createdAt",
    },
  ];
  //记录选中的id
  const [selectedIds, setSelectIds] = useState<number[]>([]);
  const TableElem = (
    <>
      <div style={{ marginBottom: "16px" }}>
        <Space>
          <Button
            size="small"
            type="primary"
            disabled={selectedIds.length === 0}
            onClick={() => {
              recover();
            }}
          >
            恢复
          </Button>
          <Button
            size="small"
            color="danger"
            type="default"
            danger
            disabled={selectedIds.length === 0}
            onClick={del}
          >
            彻底删除
          </Button>
        </Space>
      </div>
      <Table
        dataSource={list}
        columns={tableColumns}
        pagination={false}
        rowKey={(q: any) => q._id}
        rowSelection={{
          onChange: (selectedRowKeys) => {
            setSelectIds(selectedRowKeys as number[]);
          },
        }}
      />
    </>
  );
  //恢复
  const { run: recover } = useRequest(
    async () => {
      //用于便利数组 去执行异步函数 ES6
      for await (const id of selectedIds) {
        await updataQuestionService(id, { isDeleted: false });
      }
    },
    {
      manual: true,
      debounceWait: 500, //防抖
      onSuccess() {
        message.success("恢复成功");
        refresh(); //手动刷新列表
        setSelectIds([]);
      },
    }
  );
  //彻底删除
  //确认删除
  const { run: confirmDel } = useRequest(
    async () => {
      const data = await deleteQuestionService(selectedIds);
      return data;
    },
    {
      manual: true,
      onSuccess(res) {
        message.success("删除成功");
        refresh();
        setSelectIds([]);
      },
    }
  );
  function del() {
    confirm({
      title: "确认删除当前问卷？",
      icon: <ExclamationCircleFilled />,
      content: "删除之后不可找回，请仔细核对",
      okText: "确认 ",
      okType: "primary",
      cancelText: "取消",
      onOk() {
        confirmDel();
      },
      onCancel() {
        console.log("Cancel");
      },
    });
  }
  return (
    <>
      <div className={styles.header}>
        <div className={styles.left}>
          <Title level={3}>回收站</Title>
        </div>
        <div className={styles.right}>
          <ListSearch />
        </div>
      </div>
      <div className={styles.content}>
        {loading && (
          <div
            style={{
              textAlign: "center",
              marginTop: "60px",
              color: "palegoldenrod",
            }}
          >
            <Spin tip="正在加载，请稍后" size="large" />
          </div>
        )}
        {!loading && list.length === 0 && <Empty description="暂无数据" />}
        {!loading && list.length > 0 && TableElem}
      </div>
      <div className={styles.footer}>
        {!loading && list.length !== 0 && <ListPage total={total} />}
      </div>
    </>
  );
};
export default Trash;
